from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from django.contrib.admin.options import IS_POPUP_VAR
from wage.models import User, Payroll, PayrollLog, RatioConfig
from .forms import PayrollCreationForm


@admin.register(RatioConfig)
class PayUserAdmin(admin.ModelAdmin):
    list_display = ('name', 'note', 'ratio')


@admin.register(User)
class PayUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (
            _('Personal info'),
            {'fields': ('first_name', 'last_name', 'email', 'date_joined', 'dob', 'sin_no', 'address', 'ctc_phone',)}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login',)}),
    )
    list_display = (
        'username', 'email', 'first_name', 'last_name', 'is_staff', 'sin_no', 'dob', 'address', 'ctc_phone',)
    search_fields = ('username', 'first_name', 'last_name', 'email', 'sin_no', 'dob', 'address', 'ctc_phone',)


# @admin.register(Payroll)
# class PayrollAdmin(admin.ModelAdmin):
#     list_display = (
#         'total_cash_income', 'total_deductions', 'net_amount',
#         'hours', 'wage_per_hr', 'wage_income',
#         'vacation_pay_ratio', 'vacation_pay',
#         'federal_tax', 'provincial_tax', 'total_tax', 'cpp', 'ei')
#     list_editable = ('hours', 'wage_per_hr', 'vacation_pay_ratio', 'federal_tax', 'provincial_tax', 'cpp', 'ei')
#     search_fields = ('hours', 'wage_per_hr')

@admin.register(PayrollLog)
class PayrollLogAdmin(admin.ModelAdmin):
    add_form_template = 'admin/wage/payrolllog/add_form.html'
    fieldsets = (
        (None, {'fields': ('user',)}),
        (_('Cash income'), {'fields': (
            ('hours', 'wage_per_hr', 'wage_income'), ('vacation_pay_ratio', 'vacation_pay'),
            ('total_cash_income', 'net_amount'),)}),
        (_('Tax deductions'), {'fields': (('federal_tax', 'provincial_tax'), 'total_tax')}),
        (_('Other deductions'), {'fields': (('cpp', 'ei'), 'total_deductions')}),
        (_('Important dates'), {'fields': ('pay_date', ('period_from', 'period_to'), 'cheque_no', 'note')}),

    )
    readonly_fields = ('wage_income', 'vacation_pay', 'total_cash_income', 'total_tax',
                       'total_deductions', 'net_amount')

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            # 'fields': ('user', 'hours', 'wage_per_hr', 'vacation_pay_ratio'),
            'fields': ('user', 'hours'),
        }),
    )

    add_form = PayrollCreationForm

    list_display = (
        'user', 'pay_date', 'cheque_no', 'total_cash_income',
        'total_deductions', 'net_amount', 'ei', 'cpp', 'total_tax',)
    list_editable = ()
    list_filter = ('user',)
    search_fields = ('user', 'hours', 'wage_per_hr')
    date_hierarchy = 'pay_date'

    # fields = ('user', 'pay_date', ('period_from', 'period_to'), 'cheque_no', 'note')
    def get_readonly_fields(self, request, obj=None):
        """
        Hook for specifying custom readonly fields.
        """
        if obj is not None:
            return list(self.readonly_fields) + ['user', ]
        return self.readonly_fields

    def get_fieldsets(self, request, obj=None):
        if not obj:
            return self.add_fieldsets
        return super().get_fieldsets(request, obj)

    def get_form(self, request, obj=None, **kwargs):
        """
        Use special form during user creation
        """
        defaults = {}
        if obj is None:
            defaults['form'] = self.add_form
        defaults.update(kwargs)
        return super().get_form(request, obj, **defaults)

    def save_model(self, request, obj, form, change):
        payroll = Payroll.objects.get_or_create(user=obj.user, hours=obj.hours)[0]
        if change:
            payroll.wage_per_hr = form.data['wage_per_hr']
            payroll.vacation_pay_ratio = form.data['vacation_pay_ratio']
            payroll.federal_tax = form.data['federal_tax']
            payroll.provincial_tax = form.data['provincial_tax']
            payroll.cpp = form.data['cpp']
            payroll.ei = form.data['ei']
            payroll.save(
                update_fields=('wage_per_hr', 'vacation_pay_ratio', 'federal_tax', 'provincial_tax', 'cpp', 'ei'))
        elif payroll:
            obj.wage_per_hr = payroll.wage_per_hr
            obj.vacation_pay_ratio = payroll.vacation_pay_ratio
            obj.federal_tax = payroll.federal_tax
            obj.provincial_tax = payroll.provincial_tax
            obj.cpp = payroll.cpp
            obj.ei = payroll.ei

        obj.save()

    def response_add(self, request, obj, post_url_continue=None):
        """
        Determine the HttpResponse for the add_view stage. It mostly defers to
        its superclass implementation but is customized because the User model
        has a slightly different workflow.
        """
        # We should allow further modification of the user just added i.e. the
        # 'Save' button should behave like the 'Save and continue editing'
        # button except in two scenarios:
        # * The user has pressed the 'Save and add another' button
        # * We are adding a user in a popup
        if '_addanother' not in request.POST and IS_POPUP_VAR not in request.POST:
            request.POST = request.POST.copy()
            request.POST['_continue'] = 1
        return super().response_add(request, obj, post_url_continue)
